import Cookie from 'js-cookie'

export default {
  state: {
    menu: [],
    isCollapse: false,
    currentMenu: null,
    tabsList: [{
      path: '/',
      name: 'home',
      label: '首页',
      icon: 'home'
    },]
  },
  mutations: {
    setMenu(state, val) {    //登陆生成左侧列表数据
      state.menu = val
      Cookie.set('menu', JSON.stringify(val))   //因为cookie只能保存字符串   所以需要这个方法将值序列化
    },
    clearMenu(state) {     //退出登陆删除cookie数据
      state.menu = []
      Cookie.remove('menu')
    },
    addMenu(state, router) {
      if (!Cookie.get('menu')) {
        return
      }
      let menu = JSON.parse(Cookie.get('menu'))//获取Cookie里面的值  get方法  因为上面将数据改为字符串   所以这里需要改回来
      state.menu = menu
      let currentMenu = [
        {
          path: '/',
          component: () => import(`@/views/Main`),
          children: []
        }
      ]
      menu.forEach(item => {
        if (item.children) {
          item.children = item.children.map(item => {
            item.component = () => import(`@/views/${item.url}`)        // `@/views/${item.url}`  等价于  '@/views/'+ item.url  
            return item
          })
          currentMenu[0].children.push(...item.children)
        } else {
          item.component = () => import(`@/views/${item.url}`)
          currentMenu[0].children.push(item)
        }
      })
      console.log(currentMenu, 'cur')
      router.addRoutes(currentMenu)
    },
    selectMenu(state, val) {       //这个方法会自己执行吗，  为什么不需要调用呢   在CommonAside文件里面只提交了下数据
      if (val.name !== 'home') {
        state.currentMenu = val
        let resuit = state.tabsList.findIndex(item => item.name === val.name)   //findIndex方法  如果数组没有该元素返回-1，有的话返回元素对应索引
        resuit === -1 ? state.tabsList.push(val) : ''
      } else {
        state.currentMenu = null
      }
      //   val.name === 'home' ? state.currentMenu = null : state.currentMenu = val
    },
    getMenu(state) {
      if (Cookie.get('tagList')) {
        console.log('haha')
        let tagList = JSON.parse(Cookie.get('tagList'))
        state.tabsList = tagList
      }
    },
    closeTab(state, val) {
      let resuit = state.tabsList.findIndex(item => item.name === val.name)
      state.tabsList.splice(resuit, 1)
    },
    collapseMenu(state) {
      state.isCollapse = !state.isCollapse
    }
  },
  actions: {
  },
  modules: {
  }
}